<?php

namespace lemon\repository;


use lemon\models\AppInfo;

class WechatMaterial{
	function addMaterial($appid) {
		$form_data = [
			'filename' => '3NI36D53IPZ.jpg', //国片相对于网站根目录的路径
			'content-type' => 'image/jpg', //文件类型
			'filelength' => '25825' //图文大小
		];
		$post_data = [
			"media" => "https://a.56g7.cn/pte/chn/36/3NI36D53IPZ.jpg",
			"form-data" => json_encode($form_data, 320)
		];
		$access_token = $this -> getAccessToken($appid);
		$url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={$access_token}&type=image";
		//$url = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token={$access_token}";
		$result = HttpHelper::http_post($url, $post_data);
		if($result!=""){
			$result = json_decode($result, true);
			//{"errcode":48001,"errmsg":"api unauthorized rid: 63acf6f5-6a4f9ed1-1cfa63b8"}
			return $result['media_id'];
		}
		return "";
	}
	
	function getMaterial($appid){
		$access_token = $this -> getAccessToken($appid);
		$url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token={$access_token}";
		$result = HttpHelper::http_get($url);
		var_dump($result);die;
	}
	
	//  =====================================
	//  = 获取微信公众号的 access_token=
	//  =====================================
	private function getAccessToken($appid) {
		$info = AppInfo::find()->where(['app_id'=>$appid])->select(['wechat_id', 'wechat_secret', 'access_token', 'expire_time'])->asArray()->one();
		if ($info['expire_time'] < time()) {
			$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$info['wechat_id']."&secret=".$info['wechat_secret'];
			$res = json_decode(HttpHelper::http_get($url));
			$access_token = $res -> access_token;
			if ($access_token) {
				$data['expire_time'] = time() + 7000;
				$data['access_token'] = $access_token;
				AppInfo::updateAll($data, ['app_id'=>$appid]);
			}
		} else {
			$access_token = $info['access_token'];
		}
		return $access_token;
	}
}